# app/models.py
from app import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    role = db.Column(db.String(20), default='student')
    email = db.Column(db.String(120), index=True, unique=True)

    def set_password(self, password):
        """生成密码哈希值并存储"""
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        """验证密码是否正确"""
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<User {}>'.format(self.username)


class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.String(20), unique=True, nullable=False)
    name = db.Column(db.String(64), nullable=False)
    gender = db.Column(db.String(10))
    birthdate = db.Column(db.Date)
    class_name = db.Column(db.String(50))
    scores = db.relationship('Score', backref='student', lazy=True)

    def __repr__(self):
        return '<Student {}>'.format(self.name)

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    course_code = db.Column(db.String(20), unique=True, nullable=False)
    course_name = db.Column(db.String(64), nullable=False)
    teacher = db.Column(db.String(64))
    credit = db.Column(db.Integer)
    scores = db.relationship('Score', backref='course', lazy=True)

    def __repr__(self):
        return '<Course {}>'.format(self.course_name)

class Score(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.Integer, db.ForeignKey('student.id'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('course.id'), nullable=False)
    score = db.Column(db.Float)
    semester = db.Column(db.String(20))

    def __repr__(self):
        return '<Score {}:{}={}>'.format(self.student.name, self.course.course_name, self.score)    